package ooo.reindeer.cedf.components.flow;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ooo.reindeer.cedf.Cedf;
import ooo.reindeer.cedf.Event;
import ooo.reindeer.cedf.components.handler.IErrorHandler;
import ooo.reindeer.commons.Property;
import ooo.reindeer.logging.ILogger;
import ooo.reindeer.logging.LogUtil;

/**
 * @ClassName FlowErrorHandler
 * @Author songbailin
 * @Date 2019/8/30 14:52
 * @Version 1.0
 * @Description TODO
 */
public class FlowErrorHandler implements IErrorHandler {

    protected static final ILogger logger = LogUtil.getLogger(Flow.class);

    private IErrorHandler error_handler=null;

    private Property property;

    @Override
    public boolean init(String id, Property config) {
        property=config;
        String clazz=config.getValue("","");
        if(!clazz.isEmpty()) {
            logger.info("init:id=[{}] ErrorHandler=[{}] config=[{}]", id, clazz, property);
            error_handler = Cedf.loadComponent(id, clazz, property);
        }
        return true;
    }

    @Override
    public void onError(String step, Event data, Throwable error) {

        try{
            if(error_handler==null){

                logger.warn("uncaught exception step=["+step+"] data=["+data+"]",error);
            }else{
                error_handler.onError(step,data,error);
            }
        }catch (Throwable t){
            try {
                logger.warn("uncaught exception step=[" + step + "] data=[" + data + "]", error);
                logger.error("error handler excption", t);
            }catch (Throwable t1){
                synchronized (System.err){
                    t1.printStackTrace(System.err);
                    t.printStackTrace(System.err);
                    error.printStackTrace(System.err);
                }
            }
        }
    }

}
